<?php
/**
 * 获取请求ip
 *
 * @return ip地址
 */
function ip() {
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$ip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$ip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}
function safe_replace($string)
{
	$string = str_replace('%27','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace("\"",'',$string);
	$string = str_replace('//','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace('(','',$string);
	$string = str_replace(')','',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	return $string;
}
function sendtel($DestNumber,$MsgContent)
			{
				//$file="http://sms.zxhcsd.com:8080/smsservice/smsservice.asmx/SendEx?UserId=6BE11AE936&Password=xmy3239cy&MsgContent=".urlencode($title)."\n&DestNumber=".$tel."&SendTime=".date("Y-m-d H:i:s")."&SubNumber=&BatchSendID=&BizType=26&WapUrl=";
				if(!$DestNumber) return '';
				$http = "http://sms.zxhcsd.com:8080/smsservice/smsservice.asmx/SendEx";
				$UserId='6BE11AE936';
				$Password='xmy3239cy';
				$SendTime=urlencode(date("Y-m-d H:i:s"));
				$BizType=26;
				$system='linux';
				$file = $http."?UserId=".$UserId."&Password=".$Password."&MsgContent=".urlencode($MsgContent)."&DestNumber=".$DestNumber."&SendTime=".$SendTime."&SubNumber=".$SubNumber."&BatchSendID=".$BatchSendID."&BizType=".$BizType."&WapUrl=".$WapUrl."&system=".$system;
				$fp = fopen($file,"r");
				$retMsg = fgetss($fp); // $retMsg = fgetss($fp,1024);
				fclose($fp);

			}	
function sendmail($email,$mmTitle,$mailContent)
{
  require PHPCMS_ROOT.'inc/mail/class.phpmailer.php';
  $mail = new PHPMailer();
  //$mmTitle="注册成功";
  $mail->IsSMTP();        // set mailer to use SMTP
  $mail->Host = "smtp.qq.com";  // 邮件供应商的服务器地址   specify main and backup server
  $mail->SMTPAuth = true;     // 验证开启  turn on SMTP authentication
  $mail->CharSet="";
  $mail->Username = "xt@sandib2b.com";  // 你的邮箱用户名    SMTP username
  $mail->Password = "sandi2018"; // 你的邮箱密码    SMTP password

  $mail->From = "xt@sandib2b.com";   //发件箱地址
  $mail->FromName = "三帝贸易网";                //发送者姓名
  $email=explode(',',$email);
  if(is_array($email)){
	foreach ($email as $address) {
		$mail->AddAddress($address);
	}
	 }else{
  $mail->AddAddress($email);
  }
  $mail->WordWrap = 50;  
  $mail->IsHTML(true); 
  $mail->Subject = $mmTitle;  //邮件标题
  $mail->Body    =$mailContent;
  if(!$mail->Send())
  {
	echo "Message could not be sent. <p>";
	echo "Mailer Error: " . $mail->ErrorInfo;
  }
  return true;
}
//url chuli
function urlstr($urlstr)
{
	$urlstr=str_replace(",","",$urlstr);
	$urlstr=str_replace(".","",$urlstr);
	return $urlstr;
}


// wen ben ru ku qian tai diao yong  chuli
function unhtml($fString)
{
	$fString = str_replace(CHR(32),"&nbsp;",$fString);
	$fString = str_replace(CHR(13),"",$fString);
	$fString = str_replace(CHR(10) & CHR(10),"</P><P>",$fString);
	$fString = str_replace(CHR(10),"<BR><BR>",$fString);
	return $fString;
}

 
//jie qu zhong wen zi fu chuan
function mysubstr($string, $length, $len='', $dot = '...') 
{
    $string = strip_tags($string);
			$strlen = strlen($string);
			if($strlen <= $length) return $string;
			$string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
			$strcut = '';
			if(strtolower(CHARSET) == 'utf-8')
			{
				$n = $tn = $noc = 0;
				while($n < $strlen)
				{
					$t = ord($string[$n]);
					if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
						$tn = 1; $n++; $noc++;
					} elseif(194 <= $t && $t <= 223) {
						$tn = 2; $n += 2; $noc += 2;
					} elseif(224 <= $t && $t < 239) {
						$tn = 3; $n += 3; $noc += 2;
					} elseif(240 <= $t && $t <= 247) {
						$tn = 4; $n += 4; $noc += 2;
					} elseif(248 <= $t && $t <= 251) {
						$tn = 5; $n += 5; $noc += 2;
					} elseif($t == 252 || $t == 253) {
						$tn = 6; $n += 6; $noc += 2;
					} else {
						$n++;
					}
					if($noc >= $length) break;
				}
				if($noc > $length) $n -= $tn;
				$strcut = substr($string, 0, $n);
			}
			else
			{
				$dotlen = strlen($dot);
				$maxi = $length - $dotlen - 1;
				for($i = 0; $i < $maxi; $i++)
				{
					$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
				}
			}
			$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
			return $strcut.$dot;
}
// wen ben ru ku qian tai diao yong  chuli
function html_php($content){
        $content = htmlspecialchars($content);
        $content = str_replace("\n", "<br>", $content);
        $content = str_replace("  ", "&nbsp;&nbsp;", $content);
        $content = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $content);
        return $content;
}


function imgstr($img_url,$img_w,$img_h)
{
	$img=@getimagesize($img_url);
	$w=$img[0];
	$h=$img[1];
	$a=@($img_w/$w);
	$b=@($img_h/$h);
	  if($a<1||$b<1){
		 if($a>=$b){
			echo "width='";
			echo ceil($w*$b);
			$t_h=ceil($h*$b);
			echo "' height='$t_h'";
		 }else{
			$t_w=ceil($w*$a);
			echo "width='$t_w'";
			echo " height='";
			echo ceil($h*$a);
			echo "'";
		 }
	  }else{
	   echo "width='";
	   echo $w;
	   echo "' height='";
	   echo $h;
	   echo "'";
	  }
}

function keyword($keyword)
{
	$keyword=str_replace(",","",$keyword);
	$keyword=str_replace(" ","",$keyword);
	$keyword=str_replace("/","",$keyword);
	$keyword=str_replace("\\","",$keyword);
	$keyword=str_replace("","",$keyword);
	$keyword=str_replace("?","",$keyword);
	$keyword=str_replace("|","",$keyword);
	$keyword=str_replace("&nbsp;","",$keyword);
	$title=split("",$keyword);
	$key=str_replace("Ӧ","",$title[0]);
	$key=str_replace("ṩ","",$key);
	return $key;
}

function get_client_ip()
{
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
       $ip = getenv("HTTP_CLIENT_IP");
   else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
       $ip = getenv("HTTP_X_FORWARDED_FOR");
   else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
       $ip = getenv("REMOTE_ADDR");
   else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
       $ip = $_SERVER['REMOTE_ADDR'];
   else
       $ip = "unknown";
   return($ip);
}

function delwords($str)
{
	$data= mysql_query("select word from unvalid");
	$arr=array();
	while($row = mysql_fetch_array($data))
	{
		$arr[]=$row["word"];
	}
	return str_replace($arr,'**',$str);
		
}

function delelse($str)
{
	$par=array(
		"/(\d{3,4}\-\d{6,8})|(\d{7,11})/","/(http:\/\/)?((\w+)\.|。)?(\w+)\.|。([a-zA-Z]+)(\.|。[a-zA-Z]+)?(\/([a-zA-Z\.|。\/]+))?/",
		"/(http:\/\/)?((\w+)\.|。)?(\w+)\.|。([a-zA-Z]+)(\.|。[a-zA-Z]+)?(\/([a-zA-Z\.|。\/]+))?/",
		
	);
	$replace="";
	return preg_replace($par,$replace,$str);
}

function h($text, $tags = null){
	$text	=	trim($text);
	//完全过滤注释
	$text	=	preg_replace('/<!--?.*-->/','',$text);
	//完全过滤动态代码
	$text	=	preg_replace('/<\?|\?'.'>/','',$text);
	//完全过滤js
	$text	=	preg_replace('/<script?.*\/script>/','',$text);

	$text	=	str_replace('[','&#091;',$text);
	$text	=	str_replace(']','&#093;',$text);
	$text	=	str_replace('|','&#124;',$text);
	//过滤换行符
	//$text	=	preg_replace('/\r?\n/','',$text);
	//br
	$text	=	preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
	$text	=	preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
	//过滤危险的属性，如：过滤on事件lang js
	while(preg_match('/(<[^><]+)( lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1],$text);
	}
	while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1].$mat[3],$text);
	}
	if(empty($tags)) {
		$tags = '';
	}
	//允许的HTML标签
	$text	=	preg_replace('/<('.$tags.')( [^><\[\]]*)>/i','[\1\2]',$text);
	//过滤多余html
	$text	=	preg_replace('/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml|table|td|th|tr|i|b|u|strong|img|div|strong|em|ul|ol|li|dl|dd|dt|a)[^><]*>/i','',$text);
	//过滤合法的html标签
	while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
		$text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
	}
	//转换引号
	while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
	}
	//过滤错误的单个引号
	while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
		$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
	}
	//转换其它所有不合法的 < >
	$text	=	str_replace('<','&lt;',$text);
	$text	=	str_replace('>','&gt;',$text);
	$text	=	str_replace('"','&quot;',$text);
	 //反转换
	$text	=	str_replace('[','<',$text);
	$text	=	str_replace(']','>',$text);
	$text	=	str_replace('|','"',$text);
	//过滤多余空格
	$text	=	str_replace('  ',' ',$text);
	return $text;
}
function fck($value,$id,$h=300)
{
	include (PHPCMS_ROOT."inc/fckeditor/fckeditor.php" ) ; //加载文件 
	$oFCKeditor = new FCKeditor ( $id ) ; //创建一个FCKeditor对象 ID为FCKeditor1 
	$oFCKeditor -> BasePath = SITE_URL."inc/fckeditor/" ; //设置FCKeditor路径 
	$oFCKeditor -> Value = $value; //设置默认值 
	$oFCKeditor -> Height = $h ; //设置默认值 
	$oFCKeditor -> Create () ; //创建。注意：若用到模板（如smarty）则$fck = $oFCKeditor->CreateHtml();然后把$fck抛给模板 
	
}
function set_cookie($var, $value = '', $time = 0)
{
	$time = $time > 0 ? TIME+$time : 0;
	$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	$var = COOKIE_PRE.$var;
	$_COOKIE[$var] = $value;
	if(is_array($value))
	{
		foreach($value as $k=>$v)
		{
			setcookie($var.'['.$k.']', $v, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
		}
	}
	else
	{
		setcookie($var, $value, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
	}
}

function get_cookie($var)
{
	$var = COOKIE_PRE.$var;
	return isset($_COOKIE[$var]) ? $_COOKIE[$var] : false;
}
function showpages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array(), $catid = 0)
{
	$PHPCMS['pageshtml'] ='总数：<b>{$total}</b>
<a href="{$firstpage}">首页</a><a href="{$prepage}">上一页</a><a href="{$nextpage}">下一页</a><a href="{$lastpage}">尾页</a>
页次：<b><font color="red">{$page}</font>/{$pages}</b>';
	if($num > $perpage)
	{
		$multipage = '';
		if($num > $perpage)
		{
			$page = 11;
			$offset = 4;
			$pages = ceil($num / $perpage);
			$from = $curr_page - $offset;
			$to = $curr_page + $offset;
			$more = 0;
			if($page >= $pages)
			{
				$from = 2;
				$to = $pages-1;
			}
			else
			{
				if($from <= 1)
				{
					$to = $page-1;
					$from = 2;
				}
				elseif($to >= $pages)
				{
					$from = $pages-($page-2);
					$to = $pages-1;
				}
				$more = 1;
			}
			if($urlrule == '') $urlrule = url_par('page={$page}');

			$multipage .= '总数：<b>'.$num.'</b>&nbsp;&nbsp;';

			if($curr_page>0)
			{
				$multipage .= '<a href="'.pageurl($urlrule, $curr_page-1, $array).'">上一页</a>';
				if($curr_page==1)
				{
					$multipage .= '<u><b>1</b></u> ';
				}
				elseif($curr_page>6 && $more)
				{
					$multipage .= '<a href="'.pageurl($urlrule, 1, $array).'">1</a>..';
				}
				else
				{
					$multipage .= '<a href="'.pageurl($urlrule, 1, $array).'">1</a> ';
				}
			}
			for($i = $from; $i <= $to; $i++)
			{
				if($i != $curr_page)
				{
					$multipage .= '<a href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a> ';
				}
				else
				{
					$multipage .= ' <u><b>'.$i.'</b></u> ';
				}
			}
			if($curr_page<$pages)
			{
				if($curr_page<$pages-5 && $more)
				{
					$multipage .='..<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'">下一页</a>';
				}
				else
				{
					$multipage .= '<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'">下一页</a>';
				}
			}
			elseif($curr_page==$pages)
			{
				$multipage .= ' <u><b>'.$pages.'</b></u><a href="'.pageurl($urlrule, $curr_page, $array).'">下一页</a>';
			}
		}
		return $multipage;
	}
	else
	{
		$total = $num;
		$page = $curr_page;
		if($num < 1) return '';
		if($urlrule == '') $urlrule = url_par('page={$page}');
		$pages = ceil($total/$perpage);

		$page = min($pages, $page);
		$prepage = $page - 1;
		$prepage = max($prepage, 1);
		$nextpage = $page+1;
		$nextpage = min($nextpage, $pages);
		$firstpage = pageurl($urlrule, 1, $array);
		$prepage = pageurl($urlrule, $prepage, $array);
		$nextpage = pageurl($urlrule, $nextpage, $array);
		$lastpage = pageurl($urlrule, $pages, $array);
		$urlpre = pageurl($urlrule, '', $array);
		$data = str_replace('"', '\"', $PHPCMS['pageshtml']);
		eval("\$url = \"$data\";");
		return $url;
	}
}

function pageurl($urlrule, $page, $array = array())
{
	@extract($array, EXTR_SKIP);
	if(strpos($urlrule, '|'))
	{
		$urlrules = explode('|', $urlrule);
		$urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
	}
	eval("\$url = \"$urlrule\";");
	return $url;
}
function url_par($par, $url = '')
{
	if($url == '') $url = URL;
	$pos = strpos($url, '?');
	if($pos === false)
	{
		$url .= '?'.$par;
	}
	else
	{
		$querystring = substr(strstr($url, '?'), 1);
		parse_str($par, $pars);
		foreach($pars as $k=>$v)
		{
			$querystring = _url_par($k, $v, $querystring);
		}
		$url = substr($url, 0, $pos).'?'.$querystring;
	}
	return $url;
}

function _url_par($var, $value, $querystring)
{
	if($querystring)
	{
		$pattern = "/([&]?)(".preg_quote($var)."\=)([^&]+)([&]?)/";
		$querystring = preg_match($pattern, $querystring) ? preg_replace($pattern, '${1}${2}'.$value.'${4}', $querystring) : $querystring."&$var=$value";
	}
	else
	{
		$querystring = $var.'='.$value;
	}
	return $querystring;
}
function sendmessage($data)
{
	global $db;
	$data['add_time'] = date('Y-m-d H:i:s');
	$data['ip'] = ip();
	$data['m_type'] = 10;
	$true = $db->insert('m_message', $data);
	return $true;
}
?>